#import "TextRuler.h"

#import <React/RCTConvert.h>

@implementation TextRuler

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(measureTexts:(NSArray *)dataList
                      resolver:(RCTPromiseResolveBlock)resolve
                      rejecter:(RCTPromiseRejectBlock)reject){
    NSMutableArray *resList = [[NSMutableArray alloc] init];
    
    UILabel *label = [[UILabel alloc] init];
    
    for (NSDictionary *textData in dataList) {
        NSString *fontSize = [textData objectForKey: @"fontSize"];
        NSString *width = [textData objectForKey: @"maxWidth"];
        NSArray *texts = [textData objectForKey: @"texts"];
        
        if (fontSize == nil
            || width == nil
            || texts == nil) {
            [resList addObject: @[]];
            continue;
        }
        
        NSString *lineHeight = [textData objectForKey: @"lineHeight"];
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        if (lineHeight != nil) {
            [paragraph setMinimumLineHeight: [RCTConvert CGFloat: lineHeight]];
            [paragraph setMaximumLineHeight: [RCTConvert CGFloat: lineHeight]];
        }
        
        UIFont *font = [UIFont systemFontOfSize: [fontSize doubleValue]];
        
        NSMutableArray *resArray = [[NSMutableArray alloc] init];
        for (NSString *text in texts) {
            NSAttributedString *attrStr = [[NSAttributedString alloc]
                  initWithString: text
                      attributes: @{
              NSParagraphStyleAttributeName: paragraph,
                        NSFontAttributeName: font
                      }
            ];
            
            label.attributedText = attrStr;
            label.numberOfLines = 0;
            CGSize size = [label sizeThatFits: CGSizeMake([RCTConvert CGFloat: width], CGFLOAT_MAX)];
            
            NSNumber *resHeight;
            NSString *resStr = [NSString stringWithFormat: @"%0.1f", size.height];
            if ([resStr containsString: @".5"]) {
                resHeight = [NSNumber numberWithFloat: size.height + 0.5f];
            }else {
                resHeight = [NSNumber numberWithFloat: size.height];
            }
            
            [resArray addObject: resHeight];
        }
        
        [resList addObject: resArray];
    }
    
    resolve(resList);
}

@end
